package fr.synchrone.starsudoku.provider;

import java.util.HashMap;

import android.content.ContentProvider;
import android.content.ContentUris;
import android.content.ContentValues;
import android.content.Context;
import android.content.UriMatcher;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.database.sqlite.SQLiteQueryBuilder;
import android.net.Uri;
import android.text.TextUtils;
import android.util.Log;

public class PlayerProvider extends ContentProvider{
	
    private static final String TAG = "PlayerProvider";

    private static final String DATABASE_NAME = "starsudoku_player.db";
    private static final int DATABASE_VERSION = 2;
    private static final String PLAYERS_TABLE_NAME = "players";

    private static HashMap<String, String> sPlayersProjectionMap;

    private static final int PLAYERS = 1;
    private static final int PLAYER_ID = 2;

    private static final UriMatcher sUriMatcher;
    
    static {
        sUriMatcher = new UriMatcher(UriMatcher.NO_MATCH);
        sUriMatcher.addURI(Players.AUTHORITY, "players", PLAYERS);
        sUriMatcher.addURI(Players.AUTHORITY, "players/#", PLAYER_ID);
        
        sPlayersProjectionMap = new HashMap<String, String>();
        sPlayersProjectionMap.put(Players._ID, Players._ID);
        sPlayersProjectionMap.put(Players.NAME, Players.NAME);
        sPlayersProjectionMap.put(Players.CONNECTION_DATE, Players.CONNECTION_DATE);
        sPlayersProjectionMap.put(Players.PLAYED_TIME, Players.PLAYED_TIME);
    }

    /**
     * This class helps open, create, and upgrade the database file.
     */
    private static class DatabaseHelper extends SQLiteOpenHelper {

        DatabaseHelper(Context context) {
            super(context, DATABASE_NAME, null, DATABASE_VERSION);
        }

        @Override
        public void onCreate(SQLiteDatabase db) {
            db.execSQL("CREATE TABLE " + PLAYERS_TABLE_NAME + " ("
                    + Players._ID + " INTEGER PRIMARY KEY,"
                    + Players.NAME + " TEXT,"
                    + Players.CONNECTION_DATE + " INTEGER,"
                    + Players.PLAYED_TIME + " INTEGER"
                    + ");");
        }

        @Override
        public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
            Log.w(TAG, "Upgrading database from version " + oldVersion + " to "
                    + newVersion + ", which will destroy all old data");
            db.execSQL("DROP TABLE IF EXISTS notes");
            onCreate(db);
        }
    }

    private DatabaseHelper mOpenHelper;
	
	@Override
	public int delete(Uri uri, String selection, String[] selectionArgs) {
		return 0;
	}

	@Override
	public String getType(Uri uri) {
        switch (sUriMatcher.match(uri)) {
        case PLAYERS:
        case PLAYER_ID:
            return Players.CONTENT_ITEM_TYPE;
        default:
            throw new IllegalArgumentException("Unknown URI " + uri);
        }
	}

	@Override
	public Uri insert(Uri uri, ContentValues initialValues) {
        // Validate the requested uri
        if (sUriMatcher.match(uri) != PLAYERS) {
            throw new IllegalArgumentException("Unknown URI " + uri);
        }   

        ContentValues values;
        if (initialValues != null) {
            values = new ContentValues(initialValues);
        } else {
            values = new ContentValues();
        }

        Long now = Long.valueOf(System.currentTimeMillis());

        // Make sure that the fields are all set
        if (values.containsKey(Players.CONNECTION_DATE) == false) {
            values.put(Players.CONNECTION_DATE, now);
        }

        if (values.containsKey(Players.PLAYED_TIME) == false) {
            values.put(Players.PLAYED_TIME, 0);
        }

        if (values.containsKey(Players.NAME) == false) {
            values.put(Players.NAME, "Unkonw");
        }

        SQLiteDatabase db = mOpenHelper.getWritableDatabase();
        long rowId = db.insert(PLAYERS_TABLE_NAME, Players.NAME, values);
        
        if (rowId > 0) {
            Uri noteUri = ContentUris.withAppendedId(Players.CONTENT_URI, rowId);
            getContext().getContentResolver().notifyChange(noteUri, null);
            return noteUri;
        }

        throw new SQLException("Failed to insert row into " + uri);
	}

	@Override
	public boolean onCreate() {
        return (mOpenHelper = new DatabaseHelper(getContext())) != null;
	}

	@Override
	public Cursor query(Uri uri, String[] projection, String selection,
			String[] selectionArgs, String sortOrder) {
		
		SQLiteQueryBuilder qb = new SQLiteQueryBuilder();
        qb.setTables(PLAYERS_TABLE_NAME);

        switch (sUriMatcher.match(uri)) {

        case PLAYERS:
            qb.setProjectionMap(sPlayersProjectionMap);
            break;

        case PLAYER_ID:
            qb.setProjectionMap(sPlayersProjectionMap);
            qb.appendWhere(Players._ID + "=" + uri.getPathSegments().get(1));
            break;

        default:
            throw new IllegalArgumentException("Unknown URI " + uri);
        }

        // If no sort order is specified use the default
        String orderBy;
        if (TextUtils.isEmpty(sortOrder)) {
            orderBy = Players.DEFAULT_SORT_ORDER;
        } else {
            orderBy = sortOrder;
        }

        // Get the database and run the query
        SQLiteDatabase db = mOpenHelper.getReadableDatabase();
        Cursor c = qb.query(db, projection, selection, selectionArgs, null, null, orderBy);
        
        Log.i("query", "Cursor count: "+c.getCount());
        
        // Tell the cursor what uri to watch, so it knows when its source data changes
        c.setNotificationUri(getContext().getContentResolver(), uri);
        return c;
	}

	@Override
	public int update(Uri uri, ContentValues values, String where,
			String[] whereArgs) {
        SQLiteDatabase db = mOpenHelper.getWritableDatabase();
        int count;
        switch (sUriMatcher.match(uri)) {
        case PLAYERS:
            count = db.update(PLAYERS_TABLE_NAME, values, where, whereArgs);
            break;

        case PLAYER_ID:
            String noteId = uri.getPathSegments().get(1);
            count = db.update(PLAYERS_TABLE_NAME, values, Players._ID + "=" + noteId
                    + (!TextUtils.isEmpty(where) ? " AND (" + where + ')' : ""), whereArgs);
            break;

        default:
            throw new IllegalArgumentException("Unknown URI " + uri);
        }

        getContext().getContentResolver().notifyChange(uri, null);
        return count;
	}
	

}
